<template>
  <div style="padding:30px;">
    <el-form
    ref="elForm"
    :model="formData"
    size="mini"
    label-width="auto"
    label-position="left"
    style="margin-bottom: 10px;">

    <el-row type="flex" justify="start" align="middle" :gutter="10">
        <el-col :span="4">
            <el-form-item label="客户编号" prop="customerCode" class="tight-label" :style="{ marginBottom: '10px' }">
                <el-input v-model="formData.customerCode" placeholder="请输入客户编号" clearable style="margin-top: 0;"></el-input>
            </el-form-item>
        </el-col>
        <el-col :span="4">
            <el-form-item label="客户名称" prop="customerName" class="tight-label" :style="{ marginBottom: '10px' }">
                <el-input v-model="formData.customerName" placeholder="请输入客户名称" clearable style="margin-top: 0;"></el-input>
            </el-form-item>
        </el-col>
        <el-col :span="4">
            <el-form-item label="星级" prop="starLevel" class="tight-label" :style="{ marginBottom: '10px' }">
                <el-select v-model="formData.starLevel" placeholder="请选择" clearable style="margin-top: 0;">
                    <el-option label="一星" value="一星"></el-option>
                    <el-option label="二星" value="二星"></el-option>
                    <el-option label="三星" value="三星"></el-option>
                    <el-option label="四星" value="四星"></el-option>
                    <el-option label="五星" value="五星"></el-option>
                </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="4">
            <el-form-item label="行业" prop="industry" class="tight-label" :style="{ marginBottom: '10px' }">
                <el-select v-model="formData.industry" placeholder="请选择" clearable style="margin-top: 0;">
                    <el-option
                        v-for="item in industryOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
        </el-col>
    </el-row>

    <el-row>
        <el-col :span="24">
            <el-button type="primary" @click="handleSearch" size="mini">搜索</el-button>
            <el-button type="primary" @click="handleAdd" size="mini">新增</el-button>
            <el-button type="primary" @click="handleExport" size="mini">导出模版</el-button>

            <el-button type="primary" icon="el-icon-download" size="mini" @click="handleExportData">导出数据</el-button>
            <el-button type="primary" icon="el-icon-upload2" size="mini" @click="handleImport">导入数据</el-button>
            <el-button type="primary" @click="handleEdit" size="mini" :disabled="!selectedRow">编辑</el-button>
            <el-button type="danger" @click="handleDelete" size="mini" :disabled="!selectedRow" v-if="showDeleteButton">删除</el-button>
        </el-col>
    </el-row>

    <!-- 表格部分 -->
    <el-table
      :data="tableData"
      @selection-change="handleSelectionChange"
      class="customer-table"
      stripe
      border
      size="mini"
      :header-cell-style="{background:'#f5f7fa',color:'#606266',fontSize:'14px',fontWeight:'600',textAlign:'center'}"
      :cell-style="{fontSize:'12px',padding:'6px 0',textAlign:'center'}"
      height="650"
      style="width: 100%"
    >
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column type="index" label="序号" width="60" align="center" :index="indexMethod"></el-table-column>
        <el-table-column prop="customerCode" label="客户编号" min-width="120" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
                <a href="javascript:;" @click="viewCustomerDetail(scope.row.customerCode)" class="customer-link">
                    <strong>{{ scope.row.customerCode }}</strong>
                </a>
            </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户名称" min-width="150" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
                <span class="customer-name">{{ scope.row.customerName }}</span>
            </template>
        </el-table-column>
        <!-- <el-table-column label="联系人" width="100" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
                <span>{{ (scope.row.contacts && scope.row.contacts[0] && scope.row.contacts[0].contactName) || '--' }}</span>
            </template>
        </el-table-column>
        <el-table-column label="联系电话" width="120" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
                <span>{{ (scope.row.contacts && scope.row.contacts[0] && scope.row.contacts[0].phone) || '--' }}</span>
            </template>
        </el-table-column> -->
        <el-table-column label="区域" min-width="120" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
                <span class="region-text">{{ (scope.row.province || '') + (scope.row.city || '') + (scope.row.district || '') || '暂无' }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="address" label="详细地址" min-width="200" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
                <span class="address-text">{{ scope.row.address || '暂无' }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="companyType" label="公司类型" min-width="120" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
                <span class="company-type">{{ scope.row.companyType || '暂无' }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="companySize" label="公司规模" min-width="120" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
                <span class="company-size">{{ scope.row.companySize || '暂无' }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="manager" label="客户经理" min-width="100" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
                <span>{{ scope.row.manager || '--' }}</span>
            </template>
        </el-table-column>
        <el-table-column label="最后沟通" min-width="140" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
                <span>{{ formatDateTime(scope.row.lastCommunication) }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="starLevel" label="星级" width="80" align="center">
            <template slot-scope="scope">
                <el-tag
                  :type="getStarLevelType(scope.row.starLevel)"
                  size="mini"
                  class="star-tag"
                >
                  {{ scope.row.starLevel || '暂无' }}
                </el-tag>
            </template>
        </el-table-column>
        <!-- <el-table-column label="操作" width="120" align="center" fixed="right">
            <template slot-scope="scope">
                <el-button size="mini" type="text" @click="viewCustomerDetail(scope.row.customerCode)">查看</el-button>
                <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
            </template>
        </el-table-column> -->
    </el-table>

    <!-- 分页 -->
    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="formData.pageNum"
        :limit.sync="formData.pageSize"
        @pagination="getList"
    />
</el-form>
    <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="800px"
    class="custom-dialog"
  >
    <el-tabs v-model="activeTab">
      <!-- 客户信息 -->
      <el-tab-pane label="客户信息" name="customer">
        <el-form ref="dialogForm" :model="dialogForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="客户名称" prop="customerName">
                <el-input v-model="dialogForm.customerName" placeholder="请输入客户名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所在区域" prop="region">
                <el-cascader
                  v-model="dialogForm.region"
                  :options="regionOptions"
                  @change="handleRegionChange(dialogForm.region)"
                  placeholder="请选择地区"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系人" prop="contact">
                <el-input v-model="dialogForm.contact" placeholder="请输入联系人姓名"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="dialogForm.phone" placeholder="请输入手机号码"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="生日" prop="birthday">
                <el-date-picker
                  v-model="dialogForm.birthday"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户经理" prop="manager">
                <el-input v-model="dialogForm.manager" placeholder="请输入客户经理"/>
              </el-form-item>
            </el-col>
          </el-row>


          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="详细地址" prop="address">
                <el-input
                  v-model="dialogForm.address"
                  placeholder="请输入详细地址"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-button type="primary" @click="addContact">添加联系人</el-button>
        </el-form>
        <el-table :data="contacts" style="width: 100%">
          <el-table-column prop="contactName" label="联系人" />
          <el-table-column prop="phone" label="手机号" />
          <el-table-column prop="birthday" label="生日" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button @click="removeContact(scope.$index)" type="danger">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 公司信息 -->
      <el-tab-pane label="公司信息" name="company">
        <el-form ref="dialogForm" :model="dialogForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="公司类型" prop="companyType">
                <el-select
                  v-model="dialogForm.companyType"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in companyTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="公司规模" prop="companySize">
                <el-select
                  v-model="dialogForm.companySize"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in companySizeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属行业" prop="industry">
                <el-select
                  v-model="dialogForm.industry"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in industryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户星级" prop="starLevel">
                <el-select
                  v-model="dialogForm.starLevel"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in starLevelOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="dialogForm.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入备注信息"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>

      <!-- 开票信息 -->
      <el-tab-pane label="开票信息" name="invoice">
        <el-form ref="dialogForm" :model="dialogForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="单位名称" prop="invoiceName">
                <el-input v-model="dialogForm.invoiceName" placeholder="请输入开票名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="税号" prop="taxNumber">
                <el-input v-model="dialogForm.taxNumber" placeholder="请输入纳税人识别号"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="单位地址" prop="invoiceAddress">
                <el-input v-model="dialogForm.invoiceAddress" placeholder="请输入注册地址"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="invoicePhone">
                <el-input v-model="dialogForm.invoicePhone" placeholder="请输入开票联系电话"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开户银行" prop="bankName">
                <el-input v-model="dialogForm.bankName" placeholder="请输入开户银行名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="银行账户" prop="bankAccount">
                <el-input v-model="dialogForm.bankAccount" placeholder="请输入银行账号"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="发票备注" prop="invoiceRemark">
                <el-input
                  v-model="dialogForm.invoiceRemark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入开票相关备注信息"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitDialog">确 定</el-button>
    </div>
  </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="客户详情" :visible.sync="detailDialogVisible" width="85%" class="customer-detail-dialog">
      <div class="detail-container">
        <!-- 客户信息区域 -->
        <div class="info-section">
          <div class="section-header">
            <i class="el-icon-user"></i>
            <span class="section-title">客户信息</span>
          </div>
          <el-descriptions :column="2" border class="detail-descriptions">
            <el-descriptions-item label="客户名称">{{ detailData.customerName }}</el-descriptions-item>
            <el-descriptions-item label="客户编号">{{ detailData.customerCode }}</el-descriptions-item>
            <el-descriptions-item label="所在区域">{{ (detailData.province || '') + (detailData.city || '') + (detailData.district || '') }}</el-descriptions-item>
            <el-descriptions-item label="联系人">{{ (detailData.contacts && detailData.contacts[0] && detailData.contacts[0].contactName) || '--' }}</el-descriptions-item>
            <el-descriptions-item label="手机号码">{{ (detailData.contacts && detailData.contacts[0] && detailData.contacts[0].phone) || '--' }}</el-descriptions-item>
            <el-descriptions-item label="生日">{{ (detailData.contacts && detailData.contacts[0] && detailData.contacts[0].birthday) || '--' }}</el-descriptions-item>
            <el-descriptions-item label="客户经理">{{ detailData.manager }}</el-descriptions-item>
            <el-descriptions-item label="最后沟通时间">{{ formatDateTime(detailData.lastCommunication) }}</el-descriptions-item>
            <el-descriptions-item label="详细地址" :span="2">{{ detailData.address }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 公司信息区域 -->
        <div class="info-section">
          <div class="section-header">
            <i class="el-icon-office-building"></i>
            <span class="section-title">公司信息</span>
          </div>
          <el-descriptions :column="2" border class="detail-descriptions">
            <el-descriptions-item label="公司类型">{{ detailData.companyType }}</el-descriptions-item>
            <el-descriptions-item label="公司规模">{{ detailData.companySize }}</el-descriptions-item>
            <el-descriptions-item label="所属行业">{{ detailData.industry }}</el-descriptions-item>
            <el-descriptions-item label="客户星级">{{ detailData.starLevel }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">{{ detailData.remark }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 发票信息区域 -->
        <div class="info-section">
          <div class="section-header">
            <i class="el-icon-document"></i>
            <span class="section-title">开票信息</span>
          </div>
          <el-descriptions :column="2" border class="detail-descriptions">
            <el-descriptions-item label="发票编号">{{ invoiceData.invoiceCode || '--' }}</el-descriptions-item>
            <el-descriptions-item label="发票类型">{{ invoiceData.invoiceType || '--' }}</el-descriptions-item>
            <el-descriptions-item label="单位名称">{{ invoiceData.invoiceName || '--' }}</el-descriptions-item>
            <el-descriptions-item label="税号">{{ invoiceData.taxNumber || '--' }}</el-descriptions-item>
            <el-descriptions-item label="单位地址">{{ invoiceData.invoiceAddress || '--' }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ invoiceData.invoicePhone || '--' }}</el-descriptions-item>
            <el-descriptions-item label="开户银行">{{ invoiceData.bankName || '--' }}</el-descriptions-item>
            <el-descriptions-item label="银行账号">{{ invoiceData.bankAccount || '--' }}</el-descriptions-item>
            <el-descriptions-item label="发票备注" :span="2">{{ invoiceData.remark || '--' }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :action="upload.url"
         :headers="upload.headers"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入结果弹窗 -->
    <el-dialog :title="importResultDialog.title" :visible.sync="importResultDialog.visible" width="500px" append-to-body>
      <div class="import-result-content">
        <div v-if="importResultDialog.isSuccess" class="success-message">
          <i class="el-icon-success" style="color: #67C23A; font-size: 20px; margin-right: 8px;"></i>
          <span style="color: #67C23A; font-weight: bold;">{{ importResultDialog.content }}</span>
        </div>
        <div v-else class="error-message">
          <i class="el-icon-error" style="color: #F56C6C; font-size: 20px; margin-right: 8px;"></i>
          <div style="color: #F56C6C;">
            <div v-for="(line, index) in importResultDialog.content.split('\n')" :key="index" style="margin-bottom: 8px;">
              <span v-if="line.trim()" :style="{ fontWeight: index === 0 ? 'bold' : 'normal' }">{{ line }}</span>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="importResultDialog.visible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import moment from 'moment';
import { add, list, update, getDetail,delCustomer } from "@/api/monitor/customer";
import { regionData } from 'element-china-area-data'
import { getToken } from "@/utils/auth";

export default {
  data() {
    return {
      activeTab: 'customer',
      // 在这里定义表单验证规则
      rules: {
        customerName: [
          { required: true, message: '请输入客户名称', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        industry: [
          { required: true, message: '请选择所属行业', trigger: 'change' }
        ],
        region: [
          { required: true, message: '请选择所在地区', trigger: 'change' }
        ],
        companyType: [
          { required: true, message: '请选择公司类型', trigger: 'change' }
        ],
        companySize: [
          { required: true, message: '请选择公司规模', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择客户经理', trigger: 'change' }
        ]
      } ,


      showDeleteButton:true,
      detailData: {}, // 用于存储详情数据
      invoiceData: {}, // 用于存储发票信息数据

      dialogRules: {
        customerName: [
          { required: true, message: '请输入客户名称', trigger: 'blur' }
        ],
        companyType: [
          { required: true, message: '请选择公司类型', trigger: 'change' }
        ],
        industry: [
          { required: true, message: '请选择行业', trigger: 'change' }
        ],
        manager: [
          { required: true, message: '请选择客户经理', trigger: 'change' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      }  ,


      // 搜索表单数据
      formData: {
        pageNum: 1,
        pageSize: 15,
        customerName: '',
        customerCode: '',
        status: 'pending', // 默认待定
        industry: '',
        starLevel: ''
      },
      // 表格数据
      tableData: [],
      total: 0,
      selectedRow: null,

      // 对话框相关
      dialogVisible: false,
      dialogTitle: '新增客户',
      isEdit: false,
      detailDialogVisible: false,

      // 下拉选项
      industryOptions: [
        { value: '制造业', label: '制造业' },
        { value: 'IT/互联网', label: 'IT/互联网' },
        { value: '金融业', label: '金融业' },
        { value: '房地产', label: '房地产' },
        { value: '零售业', label: '零售业' },
        { value: '服务业', label: '服务业' },
        { value: '农林牧渔', label: '农林牧渔' },
        { value: '物流运输', label: '物流运输' },
        { value: '能源环保', label: '能源环保' },
        { value: '其他行业', label: '其他行业' }
      ], // 行业选项
      regionOptions: regionData,  // 区域选项
      companyTypeOptions: [
        { label: '国企', value: '国企' },
        { label: '私企', value: '私企' },
        { label: '政府', value: '政府' },
        { label: '个人', value: '个人' }
      ],
      starLevelOptions: [
        { label: '一星', value: '一星' },
        { label: '二星', value: '二星' },
        { label: '三星', value: '三星' },
        { label: '四星', value: '四星' },
        { label: '五星', value: '五星' }
      ],
      companySizeOptions: [
        { label: '<50人', value: '<50' },
        { label: '50-150人', value: '50-150' },
        { label: '150-300人', value: '150-300' },
        { label: '>300人', value: '>300' }
      ],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "Export/importCustomerList"
      },
      // 导入结果弹窗
      importResultDialog: {
        visible: false,
        title: '导入结果',
        content: '',
        isSuccess: false
      },

      // 对话框表单数据
      dialogForm: {
        province:'',
        city:'',
        district:'',
        customerName: '',
        region: [], // 用于存储选择的区域值
        address: '',
        companyType: '',
        companySize: '',
        contact: '',
        birthday: '',
        phone: '',
        industry: '',
        manager: '',
        status: '',
        lastFollow: '',
        lastCommunication: null  ,
        starLevel : '',
        remark: '', // 备注信息
        // 开票信息
        invoiceName: '',
        taxNumber: '',
        invoiceAddress: '',
        invoicePhone: '',
        bankName: '',
        bankAccount: '',
        invoiceRemark: '', // 开票备注
        contacts: [],
        type: '0'
      },
      contacts: [], // 新增的联系人数组

      // 表单验证规则
      dialogRules: {
        customerName: [
          { required: true, message: '请输入客户名称', trigger: 'blur' }
        ],
        companyType: [
          { required: true, message: '请选择公司类型', trigger: 'change' }
        ],
        industry: [
          { required: true, message: '请选择行业', trigger: 'change' }
        ],
        manager: [
          { required: true, message: '请选择客户经理', trigger: 'change' }
        ]
      }
    }
  },

  created() {
    this.getList();
    this.getIndustryOptions();
  },

  methods: {
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handleFileSuccess(response, file, fileList) {
      console.log(111111111);
      console.log(response);
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      
      // 判断是否导入成功
      const isSuccess = response.msg && (response.msg.includes('全部导入成功') || response.msg.includes('上传成功'));
      
      this.importResultDialog = {
        visible: true,
        title: '导入结果',
        content: response.msg || '导入完成',
        isSuccess: isSuccess
      };
      
      this.getList();
    },
      // 提交上传文件
      submitFileForm() {
      this.$refs.upload.submit();
    },
    addContact() {
      // 确保 birthday 为有效值
      if (this.dialogForm.birthday) {
        // 创建新的联系人对象并加入数组
        const newContact = {
          contactName: this.dialogForm.contact,
          phone: this.dialogForm.phone,
          birthday: this.dialogForm.birthday.toLocaleDateString(), // 格式化为日期字符串
        };
        this.contacts.push(newContact);
      } else {
        alert("请填写生日"); // 如果生日未填写，给出提示
      }

      // 重置表单
      this.dialogForm.contact = '';
      this.dialogForm.phone = '';
      this.dialogForm.birthday = '';
    },
    removeContact(index) {
      this.contacts.splice(index, 1);
    },

    // 区域选择改变时的处理方法
    handleRegionChange(value) {
      if (!value || value.length === 0) {
        return;
      }

      // 通过value直接获取选中值
      const [province, city, district] = value;

      // 找到对应的label
      const provinceData = this.regionOptions.find(item => item.value === province);
      if (!provinceData) return;

      const cityData = provinceData.children.find(item => item.value === city);
      if (!cityData) return;

      const districtData = cityData.children.find(item => item.value === district);
      if (!districtData) return;

      // 保存名称
      this.dialogForm.province = provinceData.label;
      this.dialogForm.city = cityData.label;
      this.dialogForm.district = districtData.label;
    },
    // 获取列表数据
    getList() {
      this.loading = true;
      console.log(this.formData)
      list(this.formData).then(response => {
        console.log(response)
        this.tableData = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 获取行业选项
    getIndustryOptions() {
      // 调用获取行业选项的API
    },

    // 搜索
    handleSearch() {
      this.formData.pageNum = 1;
      console.log(this.formData)
      this.getList();
    },

    // 新增
    handleAdd() {
      this.dialogTitle = '新增客户';
      this.isEdit = false;
      this.dialogForm = this.getEmptyDialogForm();
      this.contacts = []; // 重置联系人数组
      this.dialogVisible = true;
    },

    // 编辑
    handleEdit() {
      if (!this.selectedRow) {
        this.$message.warning('请选择要编辑的记录');
        return;
      }

      this.dialogTitle = '编辑客户';
      this.isEdit = true;

      // 先请求后台数据获取完整的客户信息和发票信息
      const customerCode = this.selectedRow.customerCode;
      getDetail(customerCode).then(response => {
        console.log('编辑获取详情数据:', response);

        const customerData = response.data.customer || {};
        const invoiceData = response.data.customerInvoice || {};

        // 处理区域数据 - 将province、city、district转换为cascader需要的数组格式
        let regionArray = [];
        if (customerData.province) {
          // 查找省份代码
          const provinceItem = this.regionOptions.find(p => p.label === customerData.province);
          if (provinceItem) {
            regionArray.push(provinceItem.value);

            // 查找城市代码
            if (customerData.city && provinceItem.children) {
              const cityItem = provinceItem.children.find(c => c.label === customerData.city);
              if (cityItem) {
                regionArray.push(cityItem.value);

                // 查找区县代码
                if (customerData.district && cityItem.children) {
                  const districtItem = cityItem.children.find(d => d.label === customerData.district);
                  if (districtItem) {
                    regionArray.push(districtItem.value);
                  }
                }
              }
            }
          }
        }

        // 将获取到的详细数据赋值给编辑表单
        this.dialogForm = {
          ...customerData,
          ...invoiceData,
          region: regionArray // 设置正确的区域数组格式
        };
        this.dialogForm.remark = customerData.remark
        this.dialogForm.invoiceRemark = invoiceData.remark
        console.log(this.dialogForm)

        // 同时保存到detailData和invoiceData供其他地方使用
        this.detailData = customerData;
        this.invoiceData = invoiceData;

        // 如果有联系人信息，也要赋值
        if (customerData.contacts && Array.isArray(customerData.contacts)) {
          this.contacts = [...customerData.contacts];
        } else {
          this.contacts = [];
        }

        // 数据加载完成后显示弹窗
        this.dialogVisible = true;
      }).catch(error => {
        console.error('获取客户详情失败:', error);
        this.$message.error('获取客户详情失败，请重试');
      });
    },

    /** 删除按钮操作 */
    handleDelete() {
      if (!this.selectedRow) {
        this.$message.warning('请选择要删除的记录');
        return;
      }

      this.dialogForm = { ...this.selectedRow };
      console.log(this.dialogForm.customerCode)

      const customerCode = this.dialogForm.customerCode;
      this.$modal.confirm('确认删除该客户吗？').then(function() {
        return delCustomer(customerCode);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },



    // 查看详情
    viewCustomerDetail(customerCode) {
      getDetail(customerCode).then(response => {
        console.log(555,response)
        this.detailData = response.data.customer;
        this.invoiceData = response.data.customerInvoice;
        this.detailDialogVisible = true;
      });
    },

    // 表格选择变化
    handleSelectionChange(selection) {
      this.selectedRow = selection.length === 1 ? selection[0] : null;
    },

    // 提交对话框
    submitDialog() {
      console.log(this.dialogForm)
      this.dialogForm.contacts = this.contacts;
      console.log(this.dialogForm)
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          const submitFunction = this.isEdit ? update : add;
          submitFunction(this.dialogForm).then(response => {
            if (response.code === 200) {
              this.$message.success(this.isEdit ? '修改成功' : '新增成功');
              this.dialogVisible = false;
              this.getList();
            }
          });
        }
      });
    },

    // 获取空的对话框表单数据
    getEmptyDialogForm() {
      return {
        customerName: '',
        region: [],
        address: '',
        companyType: '',
        companySize: '',
        contact: '',
        birthday: '',
        phone: '',
        industry: '',
        manager: '',
        status: 'pending',
        lastFollow: '',
        lastCommunication: null,
        starLevel: '',
        province: '',
        city: '',
        district: '',
        // 开票信息字段
        invoiceName: '',
        taxNumber: '',
        invoiceAddress: '',
        invoicePhone: '',
        bankName: '',
        bankAccount: '',
        contacts: []
      };
    },

     handleExportData() {
        this.download('customer/export', {
          ...this.formData
        }, `客户信息_${this.getNowDateStr()}.xlsx`)
      },
      handleExport() {
        this.download('/Export/exportCustomerTemplate', {}, `客户信息模版_${this.getNowDateStr()}.xlsx`)
      },

      getNowDateStr() {
        const now = new Date();
        return now.getFullYear() +
          String(now.getMonth() + 1).padStart(2, '0') +
          String(now.getDate()).padStart(2, '0') +
          String(now.getHours()).padStart(2, '0') +
          String(now.getMinutes()).padStart(2, '0');
      },
      handleImport() {
        this.upload.title = "用户导入";
        this.upload.open = true;
      },

      // 获取星级标签类型
      getStarLevelType(starLevel) {
        const starMap = {
          '一星': 'info',
          '二星': 'warning',
          '三星': 'primary',
          '四星': 'success',
          '五星': 'danger'
        };
        return starMap[starLevel] || 'info';
      },

      // 计算序列号（考虑分页）
      indexMethod(index) {
        return (this.formData.pageNum - 1) * this.formData.pageSize + index + 1;
      },

      // 格式化日期时间为年月日时分格式
      formatDateTime(dateTime) {
        if (!dateTime) return '--';
        return moment(dateTime).format('YYYY-MM-DD HH:mm');
      },
  }
}
</script>

<style lang="scss">
/* 导入结果弹窗样式 */
.import-result-content {
  padding: 20px 0;
  text-align: left;
}

.success-message {
  display: flex;
  align-items: flex-start;
  line-height: 1.6;
}

.error-message {
  display: flex;
  align-items: flex-start;
}

.error-message > div {
  flex: 1;
  line-height: 1.6;
}

.error-message div > div {
  word-break: break-all;
  white-space: pre-wrap;
}

.custom-dialog {
  .el-dialog__body {
    padding: 20px 30px;
  }

  .el-tabs__header {
    margin: 0 0 15px;
  }


  .el-input__inner,
  .el-textarea__inner {
    border-radius: 4px;
  }

  .dialog-footer {
    text-align: center;
    padding: 15px 0 0;

    .el-button {
      padding: 10px 25px;
      border-radius: 4px;
    }
  }
}

// 客户详情对话框样式
.customer-detail-dialog {
  .el-dialog__body {
    padding: 20px;
    background: #f8f9fa;
  }

  .detail-container {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .info-section {
    background: #ffffff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    transition: box-shadow 0.3s ease;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
  }

  .section-header {
    background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
    color: white;
    padding: 15px 20px;
    display: flex;
    align-items: center;
    font-weight: 600;

    i {
      font-size: 18px;
      margin-right: 8px;
    }

    .section-title {
      font-size: 16px;
      letter-spacing: 0.5px;
    }
  }

  .detail-descriptions {
    margin: 0;
    border: none;
    border-radius: 0;

    .el-descriptions__header {
      display: none;
    }

    .el-descriptions__body {
      .el-descriptions__table {
        border-collapse: separate;
        border-spacing: 0;

        .el-descriptions-item__cell {
          border: 1px solid #ebeef5;
          border-top: none;
          padding: 12px 16px;
          vertical-align: middle;

          &.el-descriptions-item__label {
            background: #fafbfc;
            font-weight: 600;
            color: #606266;
            width: 120px;
            border-right: none;
          }

          &.el-descriptions-item__content {
            color: #303133;
            border-left: none;
          }
        }

        tr:last-child {
          .el-descriptions-item__cell {
            border-bottom: none;
          }
        }
      }
    }
  }

  .dialog-footer {
    text-align: center;
    padding: 20px 0 0;
    background: #f8f9fa;
    margin: 0 -20px -20px;
    border-top: 1px solid #ebeef5;

    .el-button {
      padding: 10px 30px;
      border-radius: 6px;
      font-weight: 500;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      }
    }
  }

  .el-date-editor,
  .el-select {
    width: 100%;
  }
}
.el-table {
  margin-top: 20px;
}
.dialog-footer {
  text-align: right;
}

/* 客户表格优化样式 */
.customer-table {
  .el-table__header-wrapper {
    th {
      padding: 8px 0 !important;
      text-align: center;
      font-weight: 600;
    }
  }

  .el-table__body-wrapper {
    td {
      padding: 6px 0 !important;
      vertical-align: middle;
    }
  }

  // 客户链接样式
  .customer-link {
    color: #409EFF;
    text-decoration: none;
    transition: all 0.3s ease;

    &:hover {
      color: #66b1ff;
      text-decoration: underline;
    }
  }

  // 客户名称样式
  .customer-name {
    color: #303133;
    font-weight: 500;
  }

  // 区域文本样式
  .region-text {
    color: #606266;
    font-size: 12px;
  }

  // 星级标签样式
  .star-tag {
    font-weight: 500;
    border-radius: 12px;
    padding: 2px 8px;
  }

  // 地址文本样式
  .address-text {
    color: #606266;
    line-height: 1.4;
  }

  // 公司类型样式
  .company-type {
    color: #909399;
    font-size: 12px;
    background: #f4f4f5;
    padding: 2px 6px;
    border-radius: 4px;
    display: inline-block;
  }

  // 公司规模样式
  .company-size {
    color: #909399;
    font-size: 12px;
    background: #ecf5ff;
    color: #409eff;
    padding: 2px 6px;
    border-radius: 4px;
    display: inline-block;
  }

  // 表格行悬停效果
  .el-table__row:hover {
    background-color: #f5f7fa !important;
  }

  // 选中行样式
  .el-table__row.current-row {
    background-color: #ecf5ff !important;
  }
}

// 表格容器样式
.el-table--border {
  border: 1px solid #ebeef5;
  border-radius: 6px;
  overflow: hidden;
}

// 表格头部样式优化
.el-table th.is-leaf {
  border-bottom: 2px solid #e4e7ed;
}

// 紧凑布局样式
.el-table--small {
  .cell {
    padding: 0 8px;
    line-height: 1.4;
  }
}
</style>
